<?php


namespace App\Http\Controllers\Admin\Reward;
use Illuminate\Http\Request;    //引用http请求类
use App\Exceptions\BasicException;
use App\Response\Response;
use \App\Http\Controllers\BaseController;

class RewardController extends BaseController
{

    /**
     * @api {put} /reward/update 更新道具
     * @apiVersion 0.1.0
     * @apiName 更新礼物
     * @apiGroup 道具管理
     *
     * @apiParam {number} id     序号,必传 新增传0
     * @apiParam {number} op_type 操作类型 必传 0删除 1添加 2编辑更新
     * @apiParam {number} type     道具类型,必传 1普通 2特殊
     * @apiParam {list} products   商品列表 [{item_id(商品ID):1,number(数量):1,weight(权重):1,type(2头像 3坐骑  4 特效 6礼物  8道具):1}]
     * @apiParam {string} name    道具名字，必传
     * @apiParam {string} remark    道具描述，必传
     * @apiParam {string} picture    道具图片，必传
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiError 98001  添加礼物失败
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 98001,
     *          "message": "errorMsg"
     *      }
     *
     */

    public function upRewardApi(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|numeric',
                'op_type' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $rewardDetails = $request->input('products');
        $opType = $request->input('op_type');
        $reward = $request->only(['id', 'type', 'name', 'picture', 'remark']);
        if ($opType == 1) { //添加
            if ($reward['id'] > 0) throw new BasicException(10001);
            $reward['active'] = 1;
            app('repo_reward')->addReward($reward, $rewardDetails);
            return Response::sendData(true);
        }
        if ($reward['id'] == 0) throw new BasicException(10001);
        if ($opType == 2) { //修改
            app('repo_reward')->upReward($reward, $rewardDetails);
            return Response::sendData(true);
        }
        //删除
        app('repo_reward')->delReward($reward);
        return Response::sendData(true);
    }
    /**
     * @api {get} /reward/list 道具列表
     * @apiVersion 0.1.0
     * @apiName 道具列表
     * @apiGroup 道具管理
     *
     * @apiParam {number} id   序号，非必传
     * @apiParam {string} name    道具名字，非必传
     * @apiParam {number} page     页数，非必传
     * @apiParam {number} perPage     页数，非必传
     * @apiSuccessExample 成功响应
    {
    "code": 200,
    "data": {
    "list": [
    {
    "id(主键id)": 161,
    "name（名字）": "道具名字",
    "picture（图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e63d1528eb2e.png",
    "type（礼物分类）": 1,普通道具 2,特殊道具
    "remark（道具描述）": 0,
    "type_name（礼物名字）": "1",
    "created_at"（创建时间）: 2010:10-10:10:10
    "updated_at"（更新时间）: 2010:10-10:10:10
    "reward_detail": [
    {
        "id": 1,
        "reward_id": 1,
        "item_id": 1,
        "number": 10,
        "weight 权重": 0,
        "ratio 概率": 0,
        "reward_item":
        {
            "id": 1,
            "name": "测试1",
            "type": 1 1积分，2头像 3坐骑  4 特效，5金币，6礼物 7魔法帽
        }
    }
    ],
    }
    ],
    "meta": {
    "page（页数）": 1,
    "limit（每页数量）": 10,
    "next（下一页）": "http://admin.rh/gift/list?=2",
    "total（总数）": 37
    }
    }
    }
     *
     */
    public function getRewardListApi(Request $request)
    {
        $id = $request->input('id', 0);
        $name = $request->input('name', '');
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 20);
        $where = [];
        if ($id) {
            $where[] = ['id','=', $id];
        }
        if ($name) {
            array_push($where,['name', 'like', "%{$name}%"]);
        }
        $rewardList = app('repo_reward')->getRewardList($where, $page, $perPage);
        foreach ($rewardList as $reward)
        {
            $currentWeight =0;
            foreach ($reward['reward_detail'] as $rewardDetail)
            {
                $currentWeight+=$rewardDetail['weight'];
            }
            if ($currentWeight<1){
                continue;
            }
            foreach ($reward['reward_detail'] as $rewardDetail)
            {
                $rewardDetail['ratio'] =  round($rewardDetail['weight']*100/$currentWeight, 4);
            }
        }

        return Response::sendData($rewardList);
    }
    /**
     * @api {put} /reward/send 赠送道具
     * @apiVersion 0.1.0
     * @apiName 赠送道具
     * @apiGroup 道具管理
     *
     * @apiParam {number} id     道具ID
     * @apiParam {number} user_codes 用户code字符串
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiError 98001  添加礼物失败
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 98001,
     *          "message": "errorMsg"
     *      }
     *
     */

    public function sendRewardApi(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|numeric',
                'user_codes' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $id = $request->input('id', 0);
        $userCodeStr = $request->input('user_codes', '');
        //获取user_id
        $usrcodes =  explode(",",$userCodeStr);
        foreach ($usrcodes as $userCode){
            $user = app('repo_sociaty')->getUserInfoByCode($userCode);
            if(empty($user)) continue;
            app('repo_reward')->sendReward($user->user_id, $id, "赠送道具");
        }
        return Response::sendData(true);
    }


    /**
     * @api {get} /reward/detail/type/list 道具详情类型列表
     * @apiVersion 0.1.0
     * @apiName 道具详情类型列表
     * @apiGroup 道具管理
     *
     * @apiParam {number} page     页数，
     * @apiParam {number} perPage     页数
     * @apiSuccessExample 成功响应
    {
    "code": 200,
    "data": [
    "{
        "id": 1,
        "name": "积分",
        "status": 1,
        "sort": 0,
        "add_time": 0,
        "picture": null
    }
    ]
    }
    ],
    "meta": {
    "page（页数）": 1,
    "limit（每页数量）": 10,
    "next（下一页）": "http://admin.rh/gift/list?=2",
    "total（总数）": 37
    }
    }
    }
     *
     */
    public function getRewardDetailTypeListApi(Request $request)
    {
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 20);
        $rewardDetailTypeList = app('repo_reward_detail_type')->rewardDetailTypeList($page, $perPage);
        foreach ($rewardDetailTypeList as $rewardDetailType)
        {
            $rewardDetailType['add_time'] = date('Y-m-d H:i:s', $rewardDetailType['add_time']);
        }
        return Response::sendData($rewardDetailTypeList);
    }
    /**
     * @api {put} /reward/detail/type/update 道具详情类型更新
     * @apiVersion 0.1.0
     * @apiName 道具详情类型更新
     * @apiGroup 道具管理
     *
     * @apiParam {number} id
     * @apiParam {string} name
     * @apiParam {number} sort
     * @apiParam {string} picture
     * @apiSuccessExample 成功响应
      {
      "code":200,
      "data":true
        }
     * @apiErrorExample 错误响应

           {
               "code": 98001,
               "message": "errorMsg"
           }
     */
    public function addRewardDetailTypeApi(Request $request)
    {
        $param = $request->only(['id', 'name', 'sort','picture']);
        $param['picture']=$param['picture']??null;
        app('repo_reward_detail_type')->addRewardDetailType($param);
        return Response::sendData(true);
    }
    /**
     * @api {put} /reward/detail/type/del 删除道具详情类型
     * @apiVersion 0.1.1
     * @apiName 删除道具详情类型
     * @apiGroup 道具管理
     *
     * @apiParam {number} id
     * @apiSuccessExample 成功响应
    {
    "code":200,
    "data":true
    }
     * * @apiErrorExample 错误响应

    {
    "code": 98001,
    "message": "errorMsg"
    }
     */
    public function delRewardDetailTypeApi(Request $request)
    {
        $id = $request->input('id', 1);
        app('repo_reward_detail_type')->delRewardDetailType($id);
        return Response::sendData(true);
    }

    /**
     * @api {get} /reward/item/list 单个道具列表
     * @apiVersion 0.1.0
     * @apiName 单个道具列表
     * @apiGroup 道具管理
     *
     * @apiParam {number} type   类型 所有的发0 其他具体发，
     * @apiParam {number} page     页数，
     * @apiParam {number} perPage     页数，
     * @apiSuccessExample 成功响应
    {
    "code": 200,
    "data": [
    {
        "id": 1,
        "picture": "jjjj",
        "name": "测试1",
        "created_at": null,
        "remark": "kkk",
        "updated_at": "2020-12-09 17:14:47",
        "active": 1,
        "type": 1,
        "reward_type": {
            "id": 1,
            "name": "积分"
        }
    }
    ],,
    "meta": {
    "page（页数）": 1,
    "limit（每页数量）": 10,
    "next（下一页）": "http://admin.rh/gift/list?=2",
    "total（总数）": 37
    }
    }
    }
     *
     */
    public function getRewardItemListApi(Request $request)
    {
        $type = $request->input('type', 0);
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 20);
        $rewardItemList = app('repo_reward_item')->getRewardItemList($type, $page, $perPage);
        return Response::sendData($rewardItemList);
    }
    /**
     * @api {put} /reward/item/update 更新或者添加道具
     * @apiVersion 0.1.1
     * @apiName 更新或者添加道具
     * @apiGroup 道具管理
     *
     * @apiParam {number} id
     * @apiParam {number} type
     * @apiParam {number} name 道具名字
     * @apiParam {string} picture 图片
     * @apiParam {number} product_id 道具对应的真实礼物的商品id
     * @apiSuccessExample 成功响应
    {
    "code":200,
    "data":true
    }
     * * @apiErrorExample 错误响应

    {
    "code": 98001,
    "message": "errorMsg"
    }
     */
    public function updateRewardItemApi(Request $request)
    {
        $rewardItem = $request->only(['id', 'name', 'picture', 'type', 'product_id']);
        app('repo_reward_item')->updateRewardItem($rewardItem);
        return Response::sendData(true);

    }
    /**
     * @api {put} /reward/item/del 删除道具
     * @apiVersion 0.1.1
     * @apiName 删除道具
     * @apiGroup 道具管理
     *
     * @apiParam {number} id
     * @apiSuccessExample 成功响应
    {
    "code":200,
    "data":true
    }
     * * @apiErrorExample 错误响应

    {
    "code": 98001,
    "message": "errorMsg"
    }
     */
    public function delewardItemApi(Request $request)
    {
        $id = $request->input('id', 20);
        app('repo_reward_item')->delewardItem($id);
        return Response::sendData(true);
    }
}
